package com.linshengjian.snowball.guard.utils;

import com.linshengjian.snowball.guard.GuardProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class TokenUtils {

    private GuardProperties properties;
    private Claims claims;

    public TokenUtils(GuardProperties properties) {
        this.properties = properties;
    }

    /**
     * 设置 token
     * @param token
     * @return
     */
    public boolean setToken(String token) {
        try {
            this.claims = Jwts.parser()
                    .setSigningKey(this.properties.getToken().getSecret())
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 获取用户
     * @return
     */
    public String getUserName() {
        return this.claims.getSubject();
    }

    /**
     * 构建Token
     * @param username
     * @return
     */
    public String generate(String username) {

        Claims claims = Jwts.claims();
        claims.setSubject(username);

        return generate(claims);
    }

    public String refresh() {
        return generate(this.claims);
    }


    /**
     * 验证是否有效
     * @return
     */
    public boolean isValid() {
        if (claims != null && claims.getExpiration().after(new Date()))
            return true;

        return false;
    }

    public Date getExpiration() {
        return claims.getExpiration();
    }

    private String generate(Claims claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + properties.getToken().getExpiration() * 1000))
                .signWith(SignatureAlgorithm.HS512, properties.getToken().getSecret())
                .compact();
    }
}
